<?php
namespace App\Repository;

use App\Model\UserIntegral;

use App\Facade\Event;
use App\Event\UserIntegral\CreateEvent;
use App\Event\UserIntegral\RebootEvent;

class UserIntegralRepository extends \HyperfStore\Repository
{
    // 放入模型
    public function build()
    {
        return new UserIntegral;
    }

    // 创建
    public function create(UserRepository $user, $data)
    {
        $this->model->user()->associate($user->model());
        
        $res = $this->save($data);
        
        if($res)
        {
            Event::dispatch(new CreateEvent($this));
        }
        
        return $res;
    }
    
    // 判断状态
    public function statusOk()
    {
        return $this->model->status == UserIntegral::STATUS_OK;
    }
    
    // 成功
    public function setStatusOk($body)
    {
        $this->model->status = UserIntegral::STATUS_OK;
        $this->model->body = $body;
        
        return $this->model->save();
    }
    
    // 失败
    public function setStatusNo($body)
    {
        $this->model->status = UserIntegral::STATUS_NO;
        $this->model->body = $body;
        
        return $this->model->save();
    }
    
    // 重试
    public function reboot()
    {
        if(!$this->statusOk())
        {
            Event::dispatch(new RebootEvent($this));
            
            return true;
        }
    }
}